//连接数据库
const mongoose = require('mongoose')
const db = "mongodb://localhost/nuxt"
const glob = require('glob')
const {resolve} = require('path')
    //连接数据库
    mongoose.connect(db, {useNewUrlParser:true}, function(err){

        　　if(err){
        
        　　　　console.log('Connection Error:' + err)
        
        　　}else{
        
        　　　　console.log('Connection success!')
        
        　　}
        
        })
    
    let maxConnectTimes = 0 
    return  new Promise((resolve,reject)=>{
    //把所有连接放到这里
        //增加数据库监听事件
        mongoose.connection.on('disconnected',()=>{
            console.log('***********数据库断开***********')
            if(maxConnectTimes<3){
                maxConnectTimes++
                mongoose.connect(db)    
            }else{
                reject()
                throw new Error('数据库出现问题，程序无法搞定，请人为修理......')
            }
        })
        mongoose.connection.on('error',err=>{
            console.log('***********数据库错误***********')
            if(maxConnectTimes<3){
                maxConnectTimes++
                mongoose.connect(db)   
            }else{
                reject(err)
                throw new Error('数据库出现问题，程序无法搞定，请人为修理......')
            }
        })
        //链接打开的时
        mongoose.connection.once('open',()=>{
            console.log('数据连接成功') 
            const Schema = mongoose.Schema;         //声明Schema
            var studentSchema = new Schema({
                name  : String,
                age   : String,
                school: {
                    type: Schema.Types.ObjectId,
                    ref : 'school'
                }
            });
            var schoolSchema = new Schema({
                name    : String,
                students: [
                    {
                        type: Schema.Types.ObjectId,
                        ref : 'student'
                    }
                ],
                city    : {
                    type: Schema.Types.ObjectId,
                    ref : 'city'
                }
            });
            var citySchema = new Schema({
                name  : String,
                school: [
                    {
                        type: Schema.Types.ObjectId,
                        ref : 'school'
                    }
                ]
            });
            var Student = mongoose.model('student', studentSchema);
            var School = mongoose.model("school", schoolSchema);
            var City = mongoose.model("city", citySchema);
            var city = new City({
              name  : '北京',
              school: []
          });
          
          city.save(function (err, city) {
              var school = new School({
                  name    : 'Test',
                  students: [],
                  city    : city._id
              });
              school.save(function (err, school) {
                  var student = new Student({
                      name  : 'Tom',
                      age   : 20,
                      school: school._id
                  });
                  student.save(function(err, student){
                      Student.findOne({name: 'Tom'})
                          .populate({
                              path: 'school',
                              populate: {path: 'city'}
                          })
                          .exec(function (err, data) {
                              console.log(data.name + ' 所在学校为：' + data.school.name + "，所在城市为：" + data.school.city.name);
                      })
                  });
              });
          });
        })
    })